<template>
  <div class="page page-usersetting">
    <div class="maincon  p-20">
      <div class="hd">账户信息</div>
      <div class="bd">
        <div class="avatar">
          <!-- <el-avatar :size="136" :src="info.avatar" /> -->
          <PublicCptGoodsAvatar :size="160" :goodsUrl="userInfo?.goodsUrl" :avatarUrl="userInfo?.avatar">
          </PublicCptGoodsAvatar>
          <div class="text" @click="editAvatar">修改头像</div>
        </div>
        <!-- line start -->
        <div class="line">
          <div class="info">
            <div class="label">用户账号</div>
            <div class="value">{{ userInfo.username }}</div>
          </div>
        </div>
        <!--  line end-->
        <!-- line start -->
        <div class="line">
          <div class="info">
            <div class="label">用户昵称</div>
            <div class="value">{{ userInfo.nickname }}</div>
          </div>
          <div class="menu" @click="editNickname">编辑用户名</div>
        </div>
        <!--  line end-->
        <!-- line start -->
        <div class="line" v-show="false">
          <div class="info">
            <div class="label">手机号</div>
            <div class="value">{{ userInfo.phone }}</div>
          </div>
          <div class="menu">绑定手机号</div>
        </div>
        <!--  line end-->
        <!-- line start -->
        <div class="line">
          <div class="info">
            <div class="label">密码</div>
            <div class="value">已设置</div>
          </div>
          <div class="menu" @click="editPassword">修改密码</div>
        </div>
        <!--  line end-->
      </div>
    </div>
    <ClientOnly>

      <el-dialog v-model="nicknameModalVisible" class="editmodal" title="修改昵称" width="606px">
        <div class="input">
          <input type="text" placeholder="请输入昵称" v-model="tempNickname" />
        </div>
        <div class="tip">
          <el-icon>
            <ElIconWarning color="#D24F37" />
          </el-icon>
          普通用户一年仅可修改一次昵称，会员用户不限制修改次数
          <div class="link" @click="goVip">
            查看会员详情
            <el-icon>
              <ElIconDArrowRight />
            </el-icon>
          </div>
        </div>
        <div class="btns">
          <div class="btn btn-cancel" @click="nicknameModalVisible = false">取消</div>
          <div class="btn btn-confirm" @click="updateNickname">确定</div>
        </div>
      </el-dialog>

      <el-dialog v-model="passwordModalVisible" class="editmodal" title="修改密码" width="606px">
        <div class="input">
          <input type="text" placeholder="现在的密码" v-model="tempOldpassword" />
        </div>
        <div class="input">
          <input type="text" placeholder="新密码" v-model="tempNewpassword" />
        </div>
        <div class="btns">
          <div class="btn btn-cancel" @click="passwordModalVisible = false">取消</div>
          <div class="btn btn-confirm" @click="updatePassword">确定</div>
        </div>
      </el-dialog>


      <el-dialog v-model="avatarModalVisible" class="editmodal" title="修改头像" width="606px">
        <div class="avatars">
          <div class="left">
            <div>
              <!-- <el-avatar :size="152" :src="info.avatar" /> -->
              <PublicCptGoodsAvatar :size="152" :goodsUrl="userInfo?.goodsUrl" :avatarUrl="tempAvatar"></PublicCptGoodsAvatar>
              <div class="text">当前头像</div>
              <div style="
								margin-top: 10px;
								display: flex;
								align-items: center;
								justify-content: center;
							">
                <el-upload action="#" ref="Upload" :limit="1" :show-file-list="false" :before-upload="beforeUpload"
                  :http-request="onUpload" :on-success="onSuccess" :disabled="disableStatus">
                  <el-button type="primary" @click="uploadEvent">点击上传</el-button>
                </el-upload>
              </div>
            </div>
          </div>
          <div class="right">
            <div class="item" v-for="(avatar, index) in avatars" @click="setTempavatar(avatar)" :key="index">
              <el-avatar :size="62" :src="avatar" />

              <el-icon :size="24" v-if="avatar == tempAvatar" color="#755afb">
                <ElIconSuccessFilled />
              </el-icon>
            </div>
          </div>
        </div>
        <div class="tip">
          <el-icon>
            <ElIconWarning color="#D24F37" />
          </el-icon>
          普通用户一年仅可上传一次头像，会员用户不限制次数
          <div class="link" @click="goVip">
            查看会员详情
            <el-icon>
              <ElIconDArrowRight />
            </el-icon>
          </div>
        </div>
        <div class="btns">
          <div class="btn btn-confirm" @click="updateAvatar">确定</div>
        </div>
      </el-dialog>
    </ClientOnly>

  </div>
</template>
<script lang="ts" setup>
import { storeToRefs } from "pinia";
import { ref, watch } from "vue";

import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
const { signIn, token, data: userInfo, status, lastRefreshedAt, signOut, getSession } = useAuth()
import { postUserModifyPassword, uploadData, refreshUserPersonInfo, postUserGetUserLogCount, postUserModifyBase } from '~/service/yapi';

import PublicCptGoodsAvatar from '~/components/public/CptGoodsAvatar.vue'

let tempNickname = ref("");
let tempOldpassword = ref("");
let tempNewpassword = ref("");
let tempAvatar = ref("");
let avatars = ref([
  "https://cdn.codinghou.cn/coding/pc/icons/avatar/a-Cat.png",
  "https://cdn.codinghou.cn/coding/pc/icons/avatar/a-D.png",
  "https://cdn.codinghou.cn/coding/pc/icons/avatar/a-Megatron.png",
  "https://cdn.codinghou.cn/coding/pc/icons/avatar/a-Morf.png",
  "https://cdn.codinghou.cn/coding/pc/icons/avatar/a-Oslow.png",
  "https://cdn.codinghou.cn/coding/pc/icons/avatar/a-Scotty.png",
  "https://cdn.codinghou.cn/coding/pc/icons/avatar/a-Skull.png",
  "https://cdn.codinghou.cn/coding/pc/icons/avatar/a-Snumpus.png",
  "https://cdn.codinghou.cn/coding/pc/icons/avatar/a-Tipp.png"
]);
// watch(
//   () => info.value?.nickname,
//   (val) => {
//     tempNickname.value = val;
//   },
//   { immediate: true }
// );

// watch(
//   () => info.value?.avatar,
//   (val) => {
//     tempAvatar.value = val;
//   },
//   { immediate: true }
// );
let nicknameModalVisible = ref(false);
let avatarModalVisible = ref(false);
let passwordModalVisible = ref(false);
let avtarModalVisible = ref(false);

function setTempavatar(avatar: any) {
  tempAvatar.value = avatar;
}
const disableStatus = ref(false);
function editAvatar() {
  tempAvatar.value = userInfo.value?.avatar
  if (userInfo?.VIPlevel < 1) {
    postUserGetUserLogCount({ type: "avatar" }).then((res: any) => {
      if (res.data > 0) {
        disableStatus.value = true;

      }
    });
  }
  avatarModalVisible.value = true;

}

function editNickname() {
  if (userInfo?.VIPlevel < 1) {
    postUserGetUserLogCount({ type: "nickname" }).then((res: any) => {
      if (res.data > 0) {
        ElMessage.error(`非会员用户昵称只能修改一次`);
        return;
      }
      nicknameModalVisible.value = true;
    });
  } else {
    nicknameModalVisible.value = true;
  }
}

function uploadEvent() {
  if (disableStatus.value) {
    ElMessage.error(`非会员用户头像只能上传一次`);
  }
}

function editPassword() {
  passwordModalVisible.value = true;
}
let router = useRouter();

function goVip() {
  router.push(`/vip/intro`);
}

function updateNickname() {
  if (!tempNickname.value) {
    return ElMessage.warning("昵称不能为空");
  } else {
    if (tempNickname.value.length > 10) {
      return ElMessage.warning("昵称长度不能超过10个字符");
    }
    postUserModifyBase({
      nickname: tempNickname.value
    })
      .then(async (res) => {
        await refreshUserPersonInfo({})
        nicknameModalVisible.value = false;

        return ElMessage.success("修改成功");
      })
      .catch((err) => {
        return ElMessage.warning(err);
      });
  }
}
function updateAvatar() {
  postUserModifyBase({
    avatar: tempAvatar.value
  })
    .then(async (res) => {
      await refreshUserPersonInfo({})

      avatarModalVisible.value = false;
      return ElMessage.success("修改成功");
    })
    .catch((err) => {
      return ElMessage.warning(err);
    });
}
function updatePassword() {
  if (!tempOldpassword.value || !tempNewpassword.value) {
    return ElMessage.warning("旧密码不能为空");
  } else {
    postUserModifyPassword({
      oldpassword: tempOldpassword.value,
      newpassword: tempNewpassword.value
    })
      .then((res) => {
        if (res.code == 1000) {
          passwordModalVisible.value = false;
          return ElMessage.success("修改成功");

        } else {
          return ElMessage.warning(res.message);
        }
      })
      .catch((err) => {
        return ElMessage.warning(err);
      });
  }
}

function beforeUpload(file: any) {
  const typeArry = [".jpg", ".png", ".jpeg"];
  const type = file.name.substring(file.name.lastIndexOf("."));
  const isImage = typeArry.indexOf(type.toLowerCase()) > -1;
  if (!isImage) {
    ElMessage.error("上传文件必须为图片");
    return;
  }

  if (file.size / 1024 / 1024 >= 5) {
    ElMessage.error(`上传文件大小不能超过 5MB!`);
    return false;
  }
}

function onSuccess(res: any, file: any, fileList: any) {
  console.log("res: ", res);
  console.log("file: ", file, fileList);
}

function onUpload(option: any) {
  const file = option.file;
  uploadData({
    file: file
  }).then((res: any) => {
    setTempavatar(res.data.data.url);
  });
}
</script>
<style lang="scss">
.page-usersetting {
  .maincon {
    max-width: 1200px;
    margin: 0 auto;
    border-radius: 12px;
    background: #ffffff;
    box-sizing: border-box;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);

    .avatar {
      width: 160px;
      margin: 0 auto 30px;
      text-align: center;

      .text {
        padding-top: 12px;
        font-size: 16px;
        color: var(--purple);
        cursor: pointer;
        transition: all 0.3s ease;
        
        &:hover {
          opacity: 0.7;
        }
      }
    }

    .hd {
      font-size: 28px;
      font-weight: 600;
      margin-bottom: 40px;
      padding-bottom: 10px;
      border-bottom: 1px solid rgba(0, 0, 0, 0.1);
      color: #333333;
    }

    .bd {
      .line {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 24px 0;
        border-bottom: 1px solid #e8e8e8;
        transition: background-color 0.2s ease;

        &:hover {
          background-color: rgba(0, 0, 0, 0.02);
        }

        .info {
          flex: 1;
        }

        .label {
          font-size: 18px;
          font-weight: 500;
          color: #333333;
        }

        .value {
          margin-top: 8px;
          font-size: 16px;
          color: #666666;
        }

        .menu {
          width: 120px;
          height: 42px;
          line-height: 42px;
          text-align: center;
          border-radius: 10px;
          border: 2px solid var(--purple);
          color: var(--purple);
          cursor: pointer;
          transition: all 0.3s ease;
          font-weight: 500;
          
          &:hover {
            background-color: var(--purple);
            color: white;
          }
        }
      }
    }
  }

  .editmodal {
    .el-dialog__header {
      margin-bottom: 20px;
    }

    .input {
      margin-bottom: 20px;
      
      input {
        width: 100%;
        padding: 12px 16px;
        border-radius: 8px;
        border: 1px solid #d9d9d9;
        background: #ffffff;
        color: #333333;
        font-size: 16px;
        
        &:focus {
          border-color: var(--purple);
          outline: none;
          box-shadow: 0 0 0 2px rgba(117, 90, 251, 0.1);
        }
      }
    }

    .tip {
      display: flex;
      align-items: center;
      padding: 12px;
      background: rgba(210, 79, 55, 0.1);
      border-radius: 8px;
      margin-bottom: 24px;
      color: #666666;
      font-size: 14px;
      
      .el-icon {
        margin-right: 10px;
      }
      
      .link {
        margin-left: 12px;
        color: var(--purple);
        cursor: pointer;
        display: flex;
        align-items: center;
        
        .el-icon {
          margin-left: 4px;
        }
      }
    }

    .btns {
      display: flex;
      justify-content: flex-end;
      gap: 16px;
      
      .btn {
        padding: 10px 24px;
        border-radius: 8px;
        cursor: pointer;
        font-weight: 500;
        
        &.btn-cancel {
          background: #f0f0f0;
          color: #666666;
          
          &:hover {
            background: #e8e8e8;
          }
        }
        
        &.btn-confirm {
          background: var(--blue);
          color: white;
          
          &:hover {
            opacity: 0.9;
          }
        }
      }
    }
    
    .avatars {
      display: flex;
      margin-bottom: 24px;
      
      .left {
        width: 180px;
        text-align: center;
        
        .text {
          margin-top: 12px;
          color: #666666;
        }
      }
      
      .right {
        flex: 1;
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 16px;
        padding-left: 24px;
        
        .item {
          position: relative;
          cursor: pointer;
          border-radius: 50%;
          width: 62px;
          height: 62px;
          
          &:hover {
            transform: scale(1.05);
          }
          
          .el-icon {
            position: absolute;
            right: -5px;
            bottom: -5px;
            background: #ffffff;
            border-radius: 50%;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
          }
        }
      }
    }
  }
}

@media only screen and (max-width: 1280px) {
  .page.page-usersetting {
    .maincon {
      width: 90%;
      max-width: 980px;
    }
  }
}

@media only screen and (max-width: 768px) {
  .page.page-usersetting {
    .maincon {
      width: 95%;
      padding: 16px;
      
      .hd {
        font-size: 24px;
        margin-bottom: 30px;
      }
      
      .bd .line {
        flex-direction: column;
        align-items: flex-start;
        
        .info {
          margin-bottom: 16px;
        }
        
        .menu {
          width: 100%;
        }
      }
    }
    
    .editmodal {
      .avatars {
        flex-direction: column;
        
        .left {
          width: 100%;
          margin-bottom: 20px;
        }
        
        .right {
          padding-left: 0;
          grid-template-columns: repeat(3, 1fr);
        }
      }
    }
  }
}
</style>